#!/usr/bin/env python
# -*- coding:utf-8 -*-
import configparser

from excel.EGI.EgiBaseTabCalStd import EgiBaseTabCalStd
from excel.LFREE.LfreeDictUtil import LfreeDictUtil

f = r'setting.ini'
config = configparser.RawConfigParser()
config.read(f, encoding='UTF8')


class EgiAdminService:
    std_array = {}

    def __init__(self, conn):
        self.conn = conn

    def do_chck_key_exist(self, key_str):
        try:
            fetch_sql = f"SELECT count(id) FROM CAL_RAW_DATA WHERE 1=1 AND `hkey` = \'%s\'" % key_str
            item = self.conn.sql_execute(fetch_sql)
            if len(item) > 0:
                return {"code": 200, "data": item[0][0] > 0}
            return {"code": 200, "data": False}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def do_load_data(self, key_str):
        try:
            fetch_sql = f"SELECT val_json FROM CAL_RAW_DATA WHERE 1=1 AND `hkey` = \'%s\'" % key_str
            item = self.conn.sql_execute(fetch_sql)
            if len(item) > 0:
                return {"code": 200, "data": item[0][0]}
            return {"code": 400, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def do_std_base_tab(self, str_param, years):
        # 这里从数据库中读取到计算数据
        use_args = LfreeDictUtil.get_json_key(str_param.replace("EGI-", ""))
        if len(use_args) != 10:
            return {"code": 500, "data": None, "message": "页面提交参数格式不正确，无法正确解析参数"}
        # STEP 拆解数据进行计算
        hitnnt = self.do_chck_key_exist(str_param)
        if hitnnt['code'] == 200:
            if hitnnt['data']:
                # 数据库拆解计算
                str_json_data = self.do_load_data(str_param)
            else:
                # 直接计算
                str_json_data = EgiBaseTabCalStd.egi_master(str_json_key=str_param, args=use_args, years=years, )
        # 展示列表
        EgiAdminService.std_array[str_param] = str_json_data['data']
        return {"code": 200, "data": EgiAdminService.std_array[str_param]}
